<?php

namespace app\common\model;

use app\common\model\factory\Category;
use app\common\model\wash\Order;
use app\common\model\wash\Serviceorder;
use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
        'join_date',
        'avatar_str',
        'qr_image_str',
        'list'
    ];

    public function getIdcardFaceTextAttr($value, $data)
    {
        return isset($data['idcard_face']) ? cdnurl($data['idcard_face'], true) : '';
    }

    public function getIdcardEmblemTextAttr($value, $data)
    {
        return isset($data['idcard_emblem']) ? cdnurl($data['idcard_emblem'], true) : '';
    }

    public function getBusinessLicenseTextAttr($value, $data)
    {
        return isset($data['business_license']) ? cdnurl($data['business_license'], true) : '';
    }

    public function getContractFileTextAttr($value, $data)
    {
        return isset($data['contract_file']) ? cdnurl($data['contract_file'], true) : '';
    }

    public function getBankImageTextAttr($value, $data)
    {
        return isset($data['bank_image']) ? cdnurl($data['bank_image'], true) : '';
    }

    public function getQrImageStrAttr($value, $data)
    {
        return isset($data['qr_image']) && $data['qr_image'] ? cdnurl($data['qr_image'], true) : '';
    }
    public function county()
    {
        return $this->belongsTo(Admin::class, 'company_id', 'id', [], 'left')->setEagerlyType(0);
    }
    public function cate()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id', [], 'left')->setEagerlyType(0);
    }
    public function shopdata()
    {
        return $this->hasMany('app\common\model\shop\Data', 'shop_id', 'id');
    }

    public function getListAttr($value, $data)
    {
        $list = [];

        if (isset($data['role'])) {
            if ($data['mobile'] != '') {
                $list = Db::name('user')->where(['mobile' => $data['mobile'], 'role' => $data['role']])->field('id, nickname')->select();
            }
        }
        return $list;
    }
    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getJoindateAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['jointime']) ? $data['jointime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }
    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarStrAttr($value, $data)
    {
        if (!$data['avatar']) {
            //如果不需要启用首字母头像，请使用
            $data['avatar'] = '/assets/img/avatar.png';
            // $data['avatar'] = letter_avatar($data['nickname']);
        }
        return cdnurl($data['avatar'], true);
    }
    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return cdnurl($value, true);
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    public function factory()
    {
        return $this->belongsTo('User', 'factory_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('User', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function company()
    {
        return $this->belongsTo('Admin', 'company_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }


    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function cmoney($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->commission;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->commission, $money, 2) : $user->commission + $money;
                //更新会员信息
                $user->save(['commission' => $after]);
                //写入日志
                CommissionLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($user_id = 0)
    {
        $user = self::get($user_id);
        if ($user->total_money >= 399 && !$user->code) {
            $user->code = generate_invite_code();
        }
        if ($user->total_money >= 399 && $user->total_money < 999) {
            $user->product_level = 1;
        }
        if ($user->total_money >= 999 && $user->total_money < 9999) {
            $user->product_level = 2;
        }
        if ($user->total_money >= 9999 && $user->total_money < 99999) {
            $user->product_level = 3;
        }
        if ($user->total_money >= 99999) {
            $user->product_level = 4;
        }
        $user->save();
    }
    /**
     * 订单分佣
     * @param int $id 订单id
     * @return int
     */
    public static function commission($money, $integral, $sn, $uid)
    {
        //普通商品购买获得积分
        if ($integral > 0) {
            ScoreLog::income($uid, $integral, 2, 501, $sn);
        }

        Db::startTrans();
        try {

            $order = Order::get(['sn' => $sn]);
            if ($order) {
                if ($order['regional_id']) {
                    $regional = Admin::get($order['regional_id']);

                    if ($regional->total_commission > 0) {
                        $money = bcmul($money, bcdiv(100 - $regional->total_commission, 100, 2), 2);
                    }

                    if ($money <= 0) {
                        Db::commit();
                        return;
                    }

                    if ($regional->superior > 0) {
                        $user = User::get($uid);
                        if ($user) {
                            $p_user = User::get($user['pid']);
                            if ($p_user) {
                                //直推分佣金额
                                $superior = bcdiv($regional->superior, 100, 2);
                                $first_money = bcmul($money, $superior, 2);
                                if ($first_money > 0)
                                    MoneyLog::income($p_user->id, $first_money, 2, 100, $sn);
                            }
                        }
                    }

                    if ($regional->regional_commission > 0) {
                        //城市公司分佣
                        $regional_commission = bcdiv($regional->regional_commission, 100, 2);
                        $regional_money = bcmul($money, $regional_commission, 2);
                        if ($regional_money > 0) {
                            MoneyLog::income(0, $regional_money, 2, 500, $sn, $order['regional_id']);
                        }
                    }
                    if ($order['shop_id']) {
                        if ($order['send_fee'] > 0) {
                            //驿站配送费分佣
                            MoneyLog::income($order['shop_id'], $order['send_fee'], 2, 201, $sn);
                        }
                        if ($regional->shop_commission > 0) {
                            //驿站分佣
                            $shop_commission = bcdiv($regional->shop_commission, 100, 2);
                            $shop_money = bcmul($money, $shop_commission, 2);
                            if ($shop_money > 0)
                                MoneyLog::income($order['shop_id'], $shop_money, 2, 200, $sn);
                        }
                    }
                    if ($order['factory_id']) {
                        if ($regional->factory_commission > 0) {
                            //门店分佣
                            $factory_commission = bcdiv($regional->factory_commission, 100, 2);
                            $factory_money = bcmul($money, $factory_commission, 2);
                            if ($factory_money > 0)
                                MoneyLog::income($order['factory_id'], $factory_money, 2, 300, $sn);
                        }
                    }
                    if ($order['company_id']) {
                        if ($regional->company_commission > 0) {
                            //区县公司分佣
                            $company_commission = bcdiv($regional->company_commission, 100, 2);
                            $company_money = bcmul($money, $company_commission, 2);

                            if ($factory_money > 0)
                                MoneyLog::income(0, $company_money, 2, 400, $sn, $order['company_id']);
                        }
                    }
                }
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            return  $th->getMessage();
        }
    }


    /**
     *家政订单分佣
     * @param int $id 订单id
     * @return int
     */
    public static function servicecommission($money, $sn)
    {
        Db::startTrans();
        try {

            $order = Serviceorder::get(['sn' => $sn]);

            if ($order) {
                if ($order['regional_id']) {
                    $regional = Admin::get($order['regional_id']);
                    if ($regional->service_total_commission > 0) {
                        $money = bcmul($money, bcdiv(100 - $regional->service_total_commission, 100, 2));
                    }
                    if ($money <= 0) {
                        Db::commit();
                        return;
                    }
                    //城市公司分佣
                    if ($regional->service_regional_commission > 0) {
                        $regional_commission = bcdiv($regional->service_regional_commission, 100, 2);
                        $regional_money = bcmul($money, $regional_commission, 2);
                        if ($regional_money > 0)
                            MoneyLog::income(0, $regional_money, 2, 500, $sn, $order['regional_id']);
                    }

                    if ($order['shop_id']) {
                        //驿站分佣
                        if ($regional->service_shop_commission > 0) {
                            $shop_commission = bcdiv($regional->service_shop_commission, 100, 2);

                            $shop_money = bcmul($money, $shop_commission, 2);

                            if ($shop_money > 0)
                                MoneyLog::income($order['shop_id'], $shop_money, 2, 200, $sn);
                        }
                    }
                    if ($order['factory_id']) {
                        //门店分佣
                        if ($regional->service_factory_commission > 0) {
                            $factory_commission = bcdiv($regional->service_factory_commission, 100, 2);
                            $factory_money = bcmul($money, $factory_commission, 2);
                            if ($factory_money > 0)
                                MoneyLog::income($order['factory_id'], $factory_money, 2, 300, $sn);
                        }
                    }
                    if ($order['company_id']) {
                        //区县公司分佣
                        if ($regional->service_company_commission > 0) {
                            $company_commission = bcdiv($regional->service_company_commission, 100, 2);
                            $company_money = bcmul($money, $company_commission, 2);
                            if ($factory_money > 0)
                                MoneyLog::income(0, $company_money, 2, 400, $sn, $order['company_id']);
                        }
                    }
                }
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            return  $th->getMessage();
        }
    }
}
